import {Component, ElementRef, Input, OnInit, ViewChild} from '@angular/core';
import {TpHttpService} from '../../service/tp-http.service';
import {UserService} from '../../service/user.service';
import {TpStorageService} from '../../service/tp-storage.service';
import {LoginRequest} from '../../entity/login-request';
import {Md5} from 'ts-md5';
import {Site} from '../../entity/site';
import {SiteService} from '../../service/site.service';
import {BaseResponse} from '../../entity/base-response';
import {User} from '../../entity/user';

@Component({
    selector: 'app-user-login-full',
    templateUrl: './user-login-full.component.html',
    styleUrls: ['./user-login-full.component.css']
})
export class UserLoginFullComponent implements OnInit {

    constructor(private httpService: TpHttpService,
                private userService: UserService,
                private siteService: SiteService,
                private storage: TpStorageService) {
    }

    @Input()
    set show(show: boolean) {

    }

    @ViewChild('loginFrame') loginFrame: ElementRef;

    loginRequest: LoginRequest = <LoginRequest>{
        userName: '',
        password: ''
    };

    ngOnInit() {
    }

    private setUser(tokenCookie: string): boolean {
        const index = tokenCookie.indexOf('=');
        if (index === -1) {
            return false;
        }
        const token = tokenCookie.substr(index + 1);
        this.storage.set(TpStorageService.KEY_TP_DOC_TOKEN, token);
        this.userService.loadUserByToken();
        return true;
    }

    submit() {
        this.siteService.get().subscribe(site => {
            this.doLogin(site);
        });
    }

    private doLogin(site: Site) {
        const password = new Md5().appendStr(site.publicKey + this.loginRequest.password).end();
        this.httpService.post('/api/user/password-login', {
            userName: this.loginRequest.userName,
            password: password
        }).subscribe((resp: BaseResponse<User>) => {
            this.userService.userLogin(resp);
        });
    }

}
